package com.feonix.support.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.feonix.common.BaseInfo;
import com.feonix.common.listener.UserSessionInfo;
import com.feonix.common.util.SpringUtil;
import com.feonix.common.util.StringUtil;
import com.feonix.common.util.mvc.ControllerUtil;
import com.feonix.common.util.mvc.JsonResult;
import com.feonix.complat.constant.Settings;
import com.feonix.complat.constant.StaticValues;
import com.feonix.complat.entity.AccessLog;
import com.feonix.complat.entity.BanList;
import com.feonix.complat.service.AccessLogService;
import com.feonix.complat.service.BanListService;
import com.feonix.complat.service.UserService;
import com.feonix.exception.LoginException;
import com.feonix.support.CurrentUser;

/**
 * 
 * @CopyRight (c)1993-2017
 * @Project m-complat-controller
 * @Comments 后台管理页面登录
 * @NameSpace com.feonix.support.controller
 * @Author Feonixzw
 * @CreateDate 2017年11月9日
 */
@Controller("com.feonix.support.controller.LogInOutController")
@RequestMapping("admin")
public class LogInOutController {

	protected Log logger = LogFactory.getLog(getClass());

	@Autowired
	private UserService userService;

	@Autowired
	private BanListService banListService;

	@Autowired
	private AccessLogService accessLogService;

	private static final String RANDCODE_KEY = "rand";

	/**
	 * 登录页面
	 * 
	 * @param response
	 * @return
	 */
	@RequestMapping("login")
	public ModelAndView login(HttpServletResponse response) {
		ModelAndView modelAndView = new ModelAndView("support/login");
		try {
			modelAndView.addObject("username",
					URLDecoder.decode(ControllerUtil.getCookieValue(StaticValues.LOGIN_COOKIE), "utf-8"));
			modelAndView.addObject("appName", BaseInfo.getAppName());
			modelAndView.addObject("version", BaseInfo.getVersion());
			modelAndView.addObject("coptRight", Settings.getSettings().getCopyRight());
			ControllerUtil.removeCookie(response, "page");
			ControllerUtil.removeCookie(response, "menu");
		} catch (UnsupportedEncodingException e) {
			logger.error("login error", e);
		}
		modelAndView.addObject("url", "dologin");
		modelAndView.addObject("isVerifyCode", Settings.getSettings().isEnableVerifyCode());
		return modelAndView;
	}

	/**
	 * 登录
	 * 
	 * @param name
	 * @param password
	 * @param randCode
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping("dologin")
	@ResponseBody
	public JsonResult doLogin(@RequestParam(value = "name", required = true) String name,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "randcode", required = false) String randCode, HttpServletResponse response,
			HttpSession session) {
		JsonResult jsonResult = JsonResult.getInstance();
		String ip = ControllerUtil.getIp();
		BanList banList = null;
		try {
			if (Settings.getSettings().isEnableVerifyCode()) {
				String rand = (String) session.getAttribute(RANDCODE_KEY);
				session.removeAttribute(RANDCODE_KEY);
				if (StringUtil.isEmpty(randCode) || !StringUtil.equalsIgnoreCase(rand, randCode)) {
					throw new LoginException("login.randcode.error");
				}
			}
			if (StringUtil.isEmpty(name) || StringUtil.isEmpty(password)) {
				throw new LoginException("login.error");
			}
			banList = banListService.checkLoginTimes(name, ip);
			if (!banList.isCanLogin()) {
				throw new LoginException("login.error");
			}
			CurrentUser user = userService.checkUserLogin(name, password, ip);
			if (user != null) {
				UserSessionInfo.setCurrentUser(user);
				ControllerUtil.addCookie(response, StaticValues.LOGIN_COOKIE, name, 60 * 60 * 24 * 7);
				banList.setLoginTimes(0);
				if (banList != null && banList.getIid() != null) {
					banListService.removeById(banList.getIid());
				}
				AccessLog accessLog = new AccessLog();
				accessLog.setIp(ip);
				accessLog.setLoginName(name);
				accessLog.setAccesstime(user.getAccessTime());
				accessLog.setUserId(user.getIid());
				accessLogService.modifyAccessLog(accessLog);
				jsonResult.setSuccess(true);
			} else {
				throw new LoginException("login.error");
			}
		} catch (LoginException e) {
			if (banList != null && "login.error".equals(e.getMessage())) {
				int last = Settings.getSettings().getLoginError() - banList.getLoginTimes() - 1;
				String message = null;
				if (last > 0) {
					message = SpringUtil.getMessage(e.getMessage());
					message += "<br/>" + SpringUtil.getMessage("login.error.limit", last);
					banList.setLoginTimes(banList.getLoginTimes() + 1);
					banListService.modify(banList);
				} else {
					message = SpringUtil.getMessage("user.login.times", Settings.getSettings().getBanTimes());
					banList.setLoginTimes(banList.getLoginTimes() + 1);
					banListService.modify(banList);
				}
				jsonResult.setMessage(message);
			} else {
				jsonResult.setMessage(e.getMessage());
			}
		}
		return jsonResult;
	}
	
	/**
	 * 注销
	 * @return
	 */
	@RequestMapping("logout")
	public ModelAndView logout() {
		UserSessionInfo.removeCurrentUser();
		ModelAndView modelAndView = new ModelAndView();
		RedirectView redirectView = new RedirectView("login");
		modelAndView.setView(redirectView);
		return modelAndView;
	}

}
